import { Router } from 'express'
import { body } from 'express-validator'
import { asyncHandler } from '../middleware/errorHandler'
import { handleValidationErrors } from '../middleware/validation'
import { authenticate, AuthRequest } from '../middleware/auth'
import { UserService } from '../services/userService'

const router = Router()
const userService = new UserService()

// All routes require authentication
router.use(authenticate)

// Get current user profile
router.get('/profile', asyncHandler(async (req: AuthRequest, res) => {
  const user = await userService.getUserById(req.user!.id)
  
  res.json({
    success: true,
    data: {
      id: user.id,
      username: user.username,
      email: user.email,
      phone: user.phone,
      nickname: user.nickname,
      avatar: user.avatar,
      role: user.role,
      createdAt: user.createdAt,
    },
  })
}))

// Update user profile
router.put('/profile', [
  body('email').optional().isEmail().withMessage('Please provide a valid email'),
  body('phone').optional().matches(/^1[3-9]\d{9}$/).withMessage('Please provide a valid phone number'),
  body('nickname').optional().isLength({ min: 1, max: 50 }).withMessage('Nickname must be between 1 and 50 characters'),
], handleValidationErrors, asyncHandler(async (req: AuthRequest, res) => {
  const updateData = req.body
  const user = await userService.updateUser(req.user!.id, updateData)
  
  res.json({
    success: true,
    data: {
      id: user.id,
      username: user.username,
      email: user.email,
      phone: user.phone,
      nickname: user.nickname,
      avatar: user.avatar,
      role: user.role,
      updatedAt: user.updatedAt,
    },
  })
}))

// Change password
router.put('/password', [
  body('currentPassword').notEmpty().withMessage('Current password is required'),
  body('newPassword').isLength({ min: 6 }).withMessage('New password must be at least 6 characters'),
  body('confirmPassword').custom((value, { req }) => {
    if (value !== req.body.newPassword) {
      throw new Error('Passwords do not match')
    }
    return true
  }),
], handleValidationErrors, asyncHandler(async (req: AuthRequest, res) => {
  const { currentPassword, newPassword } = req.body
  
  await userService.changePassword(req.user!.id, currentPassword, newPassword)
  
  res.json({
    success: true,
    message: 'Password changed successfully',
  })
}))

// Upload avatar
router.post('/avatar', asyncHandler(async (req: AuthRequest, res) => {
  // This would be handled by multer middleware
  // For now, we'll just return a success response
  res.json({
    success: true,
    message: 'Avatar uploaded successfully',
    data: {
      avatarUrl: '/uploads/avatar.jpg',
    },
  })
}))

export { router as userRouter }